// 主题类型
export type ThemeMode = 'light' | 'dark' | 'auto'

// 从localStorage获取保存的主题设置
const getStoredTheme = (): ThemeMode => {
  const stored = localStorage.getItem('echo_role_theme') as ThemeMode
  return stored || 'auto'
}

// 检测系统主题偏好
const getSystemTheme = (): 'light' | 'dark' => {
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
}

// 应用主题到DOM
const applyThemeToDOM = (theme: 'light' | 'dark') => {
  const html = document.documentElement
  if (theme === 'dark') {
    html.classList.add('dark')
  } else {
    html.classList.remove('dark')
  }
}

// 设置主题
export const setTheme = (theme: ThemeMode) => {
  localStorage.setItem('echo_role_theme', theme)
  
  let actualTheme: 'light' | 'dark'
  
  if (theme === 'auto') {
    actualTheme = getSystemTheme()
  } else {
    actualTheme = theme
  }
  
  applyThemeToDOM(actualTheme)
  
  // 触发自定义事件，通知其他组件主题已更改
  window.dispatchEvent(new CustomEvent('theme-changed', { 
    detail: { theme, actualTheme } 
  }))
}

// 获取当前主题设置
export const getCurrentTheme = (): ThemeMode => {
  return getStoredTheme()
}

// 获取当前实际应用的主题
export const getCurrentActualTheme = (): 'light' | 'dark' => {
  const theme = getStoredTheme()
  return theme === 'auto' ? getSystemTheme() : theme
}

// 初始化主题
export const initTheme = () => {
  const theme = getStoredTheme()
  setTheme(theme)
  
  // 监听系统主题变化
  const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
  mediaQuery.addEventListener('change', () => {
    const currentTheme = getStoredTheme()
    if (currentTheme === 'auto') {
      setTheme('auto') // 重新应用auto主题
    }
  })
}

// 主题选项列表
export const themeOptions = [
  { value: 'light' as ThemeMode, label: '浅色', icon: '☀️' },
  { value: 'dark' as ThemeMode, label: '深色', icon: '🌙' },
  { value: 'auto' as ThemeMode, label: '跟随系统', icon: '💻' }
] 